package com.qax.scheduler.spring.boot.autoconfigure.controller;

import com.chinacreator.c2etcd.EtcdClient;
import com.chinacreator.c2etcd.EtcdClientFactory;
import com.qax.scheduler.spring.boot.autoconfigure.entity.JobCommand;
import com.qax.scheduler.spring.boot.autoconfigure.entity.UploadJobInfo;
import com.qax.scheduler.spring.boot.autoconfigure.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
public class JobController {

    @Autowired
    private JobRepository jobRepository;

    private static EtcdClient etcdClient = EtcdClientFactory.getInstance().connect("-config",
                                                         "http://10.47.140.59:2379",
                                                         true,
                false);


    /**
     * 上报接口，处理存储逻辑
     * @param JobInfo
     * @return
     */
    @PostMapping("/serialize/identity/info/")
    public ResponseEntity<UploadJobInfo> serializeJobInfo(@RequestBody UploadJobInfo JobInfo) {
        JobInfo.setStartTime(new Date());
        UploadJobInfo jobInfo = jobRepository.saveAndFlush(JobInfo);
        return ResponseEntity.ok(jobInfo);
    }


    /**
     * 查询JOB列表
     */
    @GetMapping("/list/identity/info/")
    public ResponseEntity<List<UploadJobInfo>> listUploadJobInfo() {
        Sort sort = Sort.by(Sort.Direction.DESC,"startTime").
                and(Sort.by("updateTime"));
        //todo  加分页
//        Pageable pageable = new PageRequest(page, size, sort);
        List<UploadJobInfo> jobInfoList = jobRepository.findAll(sort);
        return ResponseEntity.ok(jobInfoList);
    }


    /**
     * 更新服务实时更新JOB状态接口
     */
    @PutMapping("/update/info/by/{jobStatus}/{jobId}/")
    public ResponseEntity<Integer> updateUploadJobInfo(@PathVariable String jobId,
                                                                   @PathVariable String jobStatus) {
        int i = jobRepository.updateJobStatusInfoByJobId(Byte.valueOf(jobStatus),
                jobId,
                new Date());
        return ResponseEntity.ok(i);
    }



    /**
     *
     * 下发JOB触发允许相关接口
     */
    @PostMapping("/trigger/")
    public ResponseEntity<Integer> triggerSchedule(@RequestBody JobCommand command) {

        return ResponseEntity.ok(null);
    }

}
